<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel读取示例</title>
    <style>
        #excelData table{
            border-collapse: collapse;
            text-align: center;
        }
    </style>
</head>
<body>
    <input type="file" id="excelFileInput" accept=".xls,.xlsx">
    <button onclick="readExcel()">读取Excel</button>
    <div id="excelData"></div>

    <script src="https://mirror.fe80.cn/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script>
        function readExcel() {
            const fileInput = document.getElementById('excelFileInput');
            const file = fileInput.files[0];
            if (!file) {
                alert('请选择一个Excel文件');
                return;
            }
            const reader = new FileReader();
            reader.onload = function (e) {
                const data = e.target.result;
                // 以二进制流方式读取得到整份excel表格对象
                const workbook = XLSX.read(data, { type: 'binary' });
                const sheetNames = workbook.SheetNames;
                const firstSheet = workbook.Sheets[sheetNames[0]];
                const dataArray = XLSX.utils.sheet_to_json(firstSheet);

                console.log(dataArray);
                // return [];
                let html = '<table border="1">';
                // 生成表头
                html += '<thead><tr>';
                for (const key in dataArray[0]) {
                    html += `<th>${key}</th>`;
                }
                html += '</tr></thead>';

                // 生成表格内容
                html += '<tbody>';
                dataArray.forEach(row => {
                    html += '<tr>';
                    for (const key in row) {
                        html += `<td>${row[key]}</td>`;
                    }
                    html += '</tr>';
                });
                html += '</tbody></table>';

                document.getElementById('excelData').innerHTML = html;
            };
            reader.readAsBinaryString(file);
        }
    </script>
</body>
</html>